<template>
  <el-tabs
    type="border-card"
    style="margin: 0 20px; height: 93vh"
    v-model="activeName"
  >
    <el-tab-pane label="累计降雨量" name="累计降雨量">
      <el-form inline :model="form">
        <el-form-item label="开始时间">
          <el-date-picker
            type="date"
            placeholder="选择开始时间"
            size="mini"
            v-model="form.startTime"
            :picker-options="startTimePicker"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            type="date"
            placeholder="选择结束时间"
            size="mini"
            v-model="form.endTime"
            :picker-options="endTimePicker"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="info" size="mini" @click="query">查询</el-button>
        </el-form-item>
      </el-form>
      <div id="rain" class="chart"></div>
      <div class="btns" v-if="hasData">
        <el-button plain type="warning" size="mini" @click="time(1)"
          >1小时</el-button
        >
        <el-button plain type="warning" size="mini" @click="time(2)"
          >2小时</el-button
        >
        <el-button plain type="warning" size="mini" @click="time(6)"
          >6小时</el-button
        >
        <el-button plain type="warning" size="mini" @click="time(24)"
          >24小时</el-button
        >
        <el-button plain type="warning" size="mini" @click="time(7)"
          >1周</el-button
        >
        <el-button plain type="warning" size="mini" @click="time(30)"
          >1月</el-button
        >
        <el-button plain type="warning" size="mini" @click="time(365)"
          >1年</el-button
        >
      </div>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import Axios from "axios";
import moment from "moment";
import * as serviceApi from "../../../common/service.config";
import { mapState } from "vuex";
Axios.defaults.withcredentials = true;

export default {
  name: "RainfallChart",
  props: {
    node: Object,
  },
  data() {
    return {
      form: {
        startTime: moment().subtract(1, "d").format(""),
        endTime: moment().format("YYYY-MM-DD"),
      },
      activeName: "累计降雨量",
      hasData: null,
      rainfallChart: null,
    };
  },
  computed: {
    ...mapState(["timeType"]),
    startTimePicker() {
      return {
        disabledDate: (time) =>
          this.form.startTime
            ? time.getTime() > new Date(this.form.endTime).getTime()
            : false,
      };
    },
    endTimePicker() {
      return {
        disabledDate: (time) =>
          this.form.endTime
            ? time.getTime() > new Date().getTime() ||
              time.getTime() < new Date(this.form.startTime).getTime()
            : false,
      };
    },
  },
  methods: {
    initRainfallChart(collectTimeData, rainfallData, queryData) {
      let chartOption = {
        title: {
          text:
            this.node.label +
            "-" +
            queryData.startTime +
            "至" +
            queryData.endTime +
            "内雨量",
          left: "center",
        },
        color: ["#7cb5ec"],
        tooltip: {
          trigger: "axis",
        },
        legend: {
          top: 30,
          data: ["雨量"],
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: { show: true },
          },
          right: "5%",
        },
        calculable: true,
        xAxis: [
          {
            type: "category",
            axisTick: {
              alignWithLabel: true,
            },
            data: (function () {
              let data = [];
              if (collectTimeData[0] != "") {
                for (let i = 0; i < collectTimeData.length; i++) {
                  data.push(
                    moment(collectTimeData[i].replace(/-/g, "/")).format(
                      "YYYY-MM-DD HH"
                    )
                  );
                }
              }
              return data;
            })(),
          },
        ],
        yAxis: [
          {
            axisLabel: {
              formatter: "{value} mm",
            },
            type: "value",
          },
        ],
        series: [
          {
            name: "雨量",
            type: "bar",
            barWidth: "60%",
            data: (function () {
              let data = [];
              for (let i = 0; i < rainfallData.length; i++) {
                data.push(rainfallData[i]);
              }
              return data;
            })(),
            itemStyle: {
              // 通常情况下：
              normal: {
                //每个柱子的颜色即为colorList数组里的每一项，如果柱子数目多于colorList的长度，则柱子颜色循环使用该数组
                color: function (params) {
                  let colorList = [];
                  for (let i = 0; i < rainfallData.length; i++) {
                    let rainFall = rainfallData[i];
                    if (rainFall >= 50) {
                      colorList.push("rgb(226, 10, 23)");
                    } else if (rainFall >= 40 && rainFall < 50) {
                      colorList.push("rgb(252, 113, 20)");
                    } else if (rainFall >= 15 && rainFall < 40) {
                      colorList.push("rgb(255, 210, 10)");
                    }
                    //  else if (rainFall >= 7 && rainFall < 15) {
                    //   colorList.push("rgb(74, 140, 254)");
                    // }
                    else {
                      colorList.push("rgb(32, 208, 254)");
                    }
                  }
                  return colorList[params.dataIndex];
                },
              },
            },
          },
        ],
        label: {
          normal: {
            show: true,
            position: "top",
            textStyle: {
              color: "black",
            },
          },
        },
      };
      this.rainfallChart.setOption(chartOption);
    },
    creatRainfallChart(result_list, queryData) {
      let collectTimeData = [];
      let rainfallData = [];
      if (result_list.length != 0) {
        for (let i = 0; i < result_list.length; i++) {
          collectTimeData.push(result_list[i].collectTime);
          rainfallData.push(result_list[i].rainFall);
        }
        this.initRainfallChart(collectTimeData, rainfallData, queryData);
      }
    },
    search(startTime, endTime) {
      // this.rainfallChart.showLoading();
      let queryData = {
        startTime,
        endTime,
      };
      queryData.timeType = this.timeType;
      // sessionStorage.setItem("startTime", queryData.startTime);
      // sessionStorage.setItem("endTime", queryData.endTime);
      this.form.startTime = queryData.startTime;
      this.form.endTime = queryData.endTime;
      Axios({
        url: serviceApi.KB_API,
        method: "post",
        data: `appMsg={"parameter":"{\\"sensorNumber\\":\\"${this.node.sensorNumber}\\",\\"startTime\\":\\"${queryData.startTime}\\",\\"endTime\\":\\"${queryData.endTime}\\",\\"tunnelNumber\\":\\"\\",\\"timeType\\":\\"${queryData.timeType}\\"}","serviceCode":"queryRainFallByDate","timestamp":"","uuid":""}`,
      }).then((res) => {
        let resultObj = res.data;
        if (
          resultObj.parameter.list != null &&
          resultObj.parameter.list != ""
        ) {
          let result_list = resultObj.parameter.list;
          this.rainfallChart.hideLoading();
          this.creatRainfallChart(result_list, queryData);
        }
      });
    },
    query() {
      this.search(
        moment(this.form.startTime).format("YYYY-MM-DD"),
        moment(this.form.endTime).format("YYYY-MM-DD")
      );
    },
    time(timeType) {
      // this.rainfallChart.showLoading();
      let queryData = {
        startTime: moment(this.form.startTime).format("YYYY-MM-DD"),
        endTime: moment(this.form.endTime).format("YYYY-MM-DD"),
      };
      queryData.timeType = timeType;
      this.$store.dispatch("getTimeType", timeType);
      Axios({
        url: serviceApi.KB_API,
        method: "post",
        data: `appMsg={"parameter":"{\\"sensorNumber\\":\\"${this.node.sensorNumber}\\",\\"startTime\\":\\"${queryData.startTime}\\",\\"endTime\\":\\"${queryData.endTime}\\",\\"tunnelNumber\\":\\"\\",\\"timeType\\":\\"${queryData.timeType}\\"}","serviceCode":"queryRainFallByDate","timestamp":"","uuid":""}`,
      }).then((res) => {
        let resultObj = res.data;
        if (
          resultObj.parameter.list != null &&
          resultObj.parameter.list != ""
        ) {
          let result_list = resultObj.parameter.list;
          this.rainfallChart.hideLoading();
          this.creatRainfallChart(result_list, queryData);
        }
      });
    },
  },
  mounted() {
    this.rainfallChart = this.$echarts.init(document.getElementById("rain"));
    // this.rainfallChart.showLoading();
    let queryData = {
      startTime: moment().subtract(1, "d").format("YYYY-MM-DD"),
      endTime: moment().format("YYYY-MM-DD"),
    };
    if (sessionStorage.getItem("startTime"))
      queryData.startTime = sessionStorage.getItem("startTime");
    if (sessionStorage.getItem("endTime"))
      queryData.endTime = sessionStorage.getItem("endTime");
    this.form.startTime = moment(queryData.startTime).format(
      "YYYY-MM-DD 00:00:00"
    );
    this.form.endTime = moment(queryData.endTime).format("YYYY-MM-DD 00:00:00");
    Axios({
      url: serviceApi.KB_API,
      method: "post",
      data: `appMsg={"parameter":"{\\"sensorNumber\\":\\"${this.node.sensorNumber}\\",\\"startTime\\":\\"${queryData.startTime}\\",\\"endTime\\":\\"${queryData.endTime}\\",\\"tunnelNumber\\":\\"\\",\\"timeType\\":\\"1\\"}","serviceCode":"queryRainFallByDate","timestamp":"","uuid":""}`,
    }).then((res) => {
      let resultObj = res.data;
      if (resultObj.parameter) {
        if (resultObj.parameter.list && resultObj.parameter.list.length != 0) {
          let result_list = resultObj.parameter.list;
          this.rainfallChart.hideLoading();
          this.creatRainfallChart(result_list, queryData);
          this.hasData = true;
          return;
        }
        this.hasData = false;
      }
    });
  },
};
</script>

<style lang="less" scoped>
.chart {
  width: 1600px;
  height: 75vh;
}
.btns {
  display: flex;
  justify-content: center;
}
</style>